package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;

public class RedisLock implements ILock{

    private StringRedisTemplate stringRedisTemplate;
    private String key;

    private final String KEY_PREFIX = "lock:";
    //保证不同JVM实例的锁不会冲突
    private final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    //Lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    //Lua脚本加载
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new org.springframework.core.io.ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public RedisLock( String key,StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.key = key;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        long id = Thread.currentThread().getId();
        String lockKey = KEY_PREFIX + key;
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(lockKey, ID_PREFIX+id, timeoutSec, TimeUnit.SECONDS);
        return success != null && success;
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                java.util.Collections.singletonList(KEY_PREFIX + key),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
